<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item :label="$t('employing_company')" prop="employerId">
        <employerSelect v-model="queryParams.employerId" @change="employerChange"></employerSelect>
      </el-form-item>
      <el-form-item :label="$t('department')" prop="employerDeptId">
        <treeselect :normalizer="normalizer" v-model="queryParams.employerDeptId" :options="deptOptions"
          :show-count="true" :placeholder="$t('please_select', { name: $t('department') })"
          style="width: 240px; height: 20px" />
      </el-form-item>
      <el-form-item :label="$t('name')" prop="employeeName">
        <el-input v-model="queryParams.employeeName" :placeholder="$t('please_enter', { name: $t('name') })" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('employee_code')" prop="employeeCode">
        <el-input v-model="queryParams.employeeCode" :placeholder="$t('please_enter', { name: $t('employee_code') })"
          clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item :label="$t('employer_name')" prop="employerName">
        <el-input v-model="queryParams.employerName" :placeholder="$t('please_enter', { name: $t('employer_name') })"
          clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item :label="$t('mobile_phone_number')" prop="employeePhone">
        <el-input v-model="queryParams.employeePhone"
          :placeholder="$t('please_enter', { name: $t('mobile_phone_number') })" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('role')" prop="roleId">
        <el-select v-model="queryParams.roleId" clearable :placeholder="$t('please_select', { name: $t('role') })">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
      $t("reset")
    }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['employee:employeeHead:employeeHeadList:add']">{{ $t("add") }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" border :max-height="tableHeight">
      <!-- <el-table-column
        label="工号"
        align="center"
        prop="employment.jobNumber"
      /> -->
      <el-table-column :label="$t('name')" align="center" prop="employeeName" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('employee_code')" align="center" prop="employeeCode" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('mobile_phone_number')" align="center" prop="employeePhone" />
      <el-table-column :label="$t('employing_company')" align="center" prop="employerName"
        :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="$t('department')" align="center" prop="employerDeptName" :show-overflow-tooltip="true">
      </el-table-column>

      <!-- <el-table-column label="邮箱" align="center" prop="electronicMail" /> -->
      <el-table-column :label="$t('role')" align="center" prop="roleId" :formatter="getRoleName" />
      <el-table-column :label="$t('remarks')" align="center" prop="remark" />
      <el-table-column :label="$t('action')" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            v-hasPermi="['employee:employeeHead:employeeHeadList:edit']" @click="handleUpdate(scope.row)">{{
      $t("modify")
    }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
            v-hasPermi="['employee:employeeHead:employeeHeadList:delete']" @click="handleDelete(scope.row)">{{
      $t("delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" :page-sizes="[10, 20, 30, 50, 100, 200]" />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item :label="$t('select_the_employee2')" v-if="!form.id" prop="employeeId">
          <employeeSelect @change="findEmployers" v-model="form.employeeId"></employeeSelect>
        </el-form-item>
        <el-form-item :label="$t('select_employing_company')" prop="employerId">
          <el-select v-model="form.employerId" :placeholder="$t('please_select', { name: $t('select_employing_company') })
            ">
            <el-option v-for="item of findEmployersList" :key="item.id" :label="item.employerName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item :label="$t('select_employing_company')" prop="employerId">
          <el-select v-model="form.employerId" :placeholder="$t('please_select', { name: $t('select_employing_company') })
      " @change="employersChange">
            <el-option v-for="item of employersList" :key="item.id" :label="item.employerName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('select_the_employee2')" v-if="!form.id" prop="employeeId">
          <el-select v-model="form.employeeId" :placeholder="$t('please_select', { name: $t('select_the_employee2') })" filterable>
            <el-option v-for="item of employeesList" :key="item.id" :label="item.employeeName"
              :value="item.id"></el-option>
          </el-select>
          <!-- <employeeSelect @change="findEmployers" v-model="form.employeeId"></employeeSelect> -->
        </el-form-item>

        <el-form-item :label="$t('employee')" v-if="form.id">
          <el-input v-model="form.employeeName" style="width: 218px;" disabled />
        </el-form-item>
        <el-form-item :label="$t('select_the_role')" prop="roleId">
          <el-select v-model="form.roleId" clearable :placeholder="$t('please_select', { name: $t('role') })">
            <el-option v-for="item in roleOptions" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('remarks')">
          <el-input v-model="form.remark" type="textarea" :rows="3"
            :placeholder="$t('please_enter', { name: $t('remarks') })"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
      $t("confirm")
    }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  addUser,
  updateUser,
} from "@/api/custom/employeeHeadList";
import { listRole } from "@/api/custom/employeeHeadRole";
import { findEmployers } from "@/api/custom/employeeList";
import employeeSelect from "@/views/components/custom/employeeSelect.vue";
import employerSelect from "@/views/components/custom/employerSelect.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect } from "@/api/system/user";
import { listUser as employerList } from "@/api/custom/employerList"
import { listEmployee } from "@/api/custom/employeeList"
export default {
  name: "User",
  components: {
    employeeSelect, employerSelect, Treeselect
  },
  data() {
    return {
      employeesList:[],
      employersList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      findEmployersList: [],
      rules: {
        employeeId: [
          {
            required: true,
            message: this.$t("cannot_empty"),
            trigger: "change",
          },
        ],
        employerId: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("employer") }),
            trigger: "change",
          },
        ],
        roleId: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("role") }),
            trigger: "change",
          },
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: undefined,
        employeePhone: undefined,
        roleId: undefined,
        employeeCode: undefined,
        employerName: undefined,
        employerId: null,
      },
    };
  },
  created() {
    this.getList();
    this.getRoleList();
    this.getEmployerList();
  },
  methods: {
    employersChange() {
      listEmployee({ employerId: this.form.employerId, pageNo: 1, pageSize: 999 }).then(res => {
        this.employeesList = res.data.records;
      })
    },
    getEmployerList() {
      employerList({ pageNum: 1, pageSize: 999 }).then(res => {
        this.employersList = res.data.records;
      })
    },
    findEmployers(data) {
      findEmployers(data.value).then((res) => {
        this.findEmployersList = res.data;
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        this.userList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getRoleList() {
      listRole({
        pageNum: 1,
        pageSize: 999,
      }).then((res) => {
        this.roleOptions = res.data.records;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        employeeId: undefined,
        roleId: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {
        id: row.id,
        employeeId: row.employeeId,
        roleId: row.roleId,
        employerId: row.employerId,
        remark: row.remark,
        employeeName: row.employeeName
      };
      this.findEmployers({
        value: row.employeeId,
      });
      this.open = true;
      this.title = this.$t("modify");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => { });
    },
    // 根据雇主查部门
    employerChange() {
      this.queryParams.employerDeptId = null;
      if (this.queryParams.employerId) {
        this.getDeptTree();
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect(this.queryParams.employerId).then((response) => {
        this.deptOptions = response.data;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children,
      };
    },
    getRoleName(row) {
      let findItem = this.roleOptions.find((item) => {
        return item.id == row.roleId;
      });
      return findItem ? findItem.roleName : "";
    },
  },
};
</script>
